package com.gitee.chessboard.parser;

import com.gitee.chessboard.enums.DictionaryType;
import com.gitee.chessboard.manager.DictionaryManager;
import com.gitee.chessboard.model.dictionary.Dictionary;
import com.gitee.chessboard.model.word.Word;
import com.gitee.chessboard.utils.NameSchemeConvert;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 支持枚举的分析器
 *
 * @author 敲代码的旺财
 * @date 2021/11/24 12:39
 */
public class DefaultEnumDictionaryParser implements EnumDictionaryParser {

    private DictionaryManager dictionaryManager;

    public DefaultEnumDictionaryParser(DictionaryManager dictionaryManager) {
        this.dictionaryManager = dictionaryManager;
    }

    /**
     * 将枚举对象解析成字典
     *
     * @param obj 枚举
     * @return 字典
     */
    @Override
    public Dictionary parser(Class<?> obj) {
        List<Word> wordList = new ArrayList<>();
        if (!obj.isEnum()) {
            throw new RuntimeException("不是枚举类型无法解析");
        }
        Method[] methods = obj.getMethods();
        Object[] enumConstants = obj.getEnumConstants();
        try {
            for (Object enumConstant : enumConstants) {
                Word newWord = dictionaryManager.getNewWord();
                newWord.setWordCode(enumConstant + "");
                newWord.setWordName(enumConstant + "");
                newWord.setDictionaryCode(obj.getSimpleName());
                for (Method method : methods) {
                    if (method.getName().startsWith("get")
                            && method.getParameterCount() == 0) {
                        Object invoke = method.invoke(enumConstant);
                        newWord.add(NameSchemeConvert.pascal2camel(method.getName().substring(3)), String.valueOf(invoke));
                    }
                }
                wordList.add(newWord);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("分析枚举失败", e);
        }
        Dictionary dictionary = dictionaryManager.getNewDictionary(wordList);
        dictionary.setDictionaryCode(obj.getSimpleName());
        dictionary.setDictionaryName(obj.getSimpleName());
        dictionary.setDictionaryType(DictionaryType.ENUMERATION);
        return dictionary;
    }
}
